
// http://blog.csdn.net/tangxiujiang/article/details/78786592

$('#upLoad').on('change',function(){  
       $('#loding').css('display','block');  
       var filePath = $(this).val(),         //获取到input的value，里面是文件的路径  
           fileFormat = filePath.substring(filePath.lastIndexOf(".")).toLowerCase(),  
           // src = '',  //转成可以在本地预览的blob格式  
           imgBase64 = '',      //存储图片的imgBase64  
           fileObj = document.getElementById('upLoad').files[0];       //上传文件的对象,要这样写才行，用jquery写法获取不到对象  
           uploadAddress = '/', 
           data = null;  
             
       // 检查是否是图片  
       if( !fileFormat.match(/.png|.jpg|.jpeg/) ) {  
           error_prompt_alert('上传错误,文件格式必须为：png/jpg/jpeg');  
           $('#loding').css('display','none');  
           return;    
       }
  
       // 对图片进行压缩  
       compress(fileObj,function(imgBase64){  
           imgBase64 = imgBase64;  
            
           // 对图片压缩成功之后，在定义上传参数，和请求；放在compress（）外面的话，则先执行request（）请求，此时imgBase64还未赋值赋值  
           // 定义上传的参数  
           data = {  
               'imgBase64':imgBase64,  
               'openid':openid  
           };
           return
  
           // 发送上传图片的请求  
           request(uploadAddress,data,function(res){  
               console.log(res.msg);  
               $('#loding').css('display','none');  
               remote_pa_img_path = res.data.remote_pa_img_path;  
               $('#viewImg').attr('src',imgBase64); //显示预览图片  
               $('#imgBox').addClass('imgBox2');  
           },function(res){  
               console.log(res.msg);  
               $('#loding').css('display','none');  
           });  
       });         
   });  
  
   // 不对图片进行压缩，直接转成base64  
   function directTurnIntoBase64(fileObj,callback){  
       var r = new FileReader();  
       // 转成base64  
       r.onload = function(){  
          //变成字符串  
           imgBase64 = r.result;  
           console.log(imgBase64);  
           callback(imgBase64);  
       }  
       r.readAsDataURL(fileObj);    //转成Base64格式  
   }  
  
   // 对图片进行压缩  
   function compress(fileObj, callback) {   
       if ( typeof (FileReader) === 'undefined') {    
           console.log("当前浏览器内核不支持base64图标压缩");    
           //调用上传方式不压缩    
           directTurnIntoBase64(fileObj,callback);  
       } else {    
           try {      
               var Orientation=null,  
                   reader = new FileReader();    
               // reader.readAsDataURL(fileObj);    
  
               //获取图片Orientation参数  
               EXIF.getData(fileObj, function() {  
                   Orientation = EXIF.getTag(this, 'Orientation');  
               });

               console.log('Orientation',  Orientation)

  
               reader.onload = function (e) {    
                   var image = $('<img/>');   
                   image.attr('src', e.target.result);    
                   image.load(function(){    
                       var data='',  
                           canvas = document.createElement('canvas'),   
                           context = canvas.getContext('2d'),  
                           imageWidth = this.width,  
                           imageHeight = this.height;  
  
  
                       //压缩图片  
                       if(imageWidth > 1000 || imageHeight > 1000) {  
                            //等比例压缩，不失真，不裁剪  
                           if( imageWidth > imageHeight){  
                               imageWidth = 1000;  
                               imageHeight = imageWidth*imageHeight/this.width;  
                           }else{  
                               imageHeight = 1000;  
                               imageWidth = imageHeight*imageWidth/this.height;  
                           }  
                       }  
  
                       //旋转到正常角度,位置偏移  
                       var angle = 0;  
                       var x =0 ,  
                           y=0,  
                           w=imageWidth,  
                           h=imageHeight;   //canvas画布  
                       // 定义画布的大小  
                       canvas.width = imageWidth;  
                       canvas.height = imageHeight;  
                       context.drawImage(this, x, y,imageWidth,imageHeight);   
  
                       /*  
                           Orientation:  
                           3:ios手机底部在左边，拍出来的横图是倒置的，需要旋转180度  
                           6:ios手机底部朝下，拍出来的照片是头在右边，需要逆时针旋转90度  
                       */  
                       switch(Orientation){  
                           case 3:  
                               rotateImg(this,'half',canvas);//转两次    
                               break;  
                           case 6:  
                               rotateImg(this,'left',canvas);    
                               break;  
                           case 8:  
                               rotateImg(this,'right',canvas);    
                               break;  
  
                           default:  
                               break;  
                       }  
                       // context.rotate(angle);    
                       // 画图  
                       // context.drawImage(this, x, y,imageWidth,imageHeight);   
                       data = canvas.toDataURL('image/jpeg');  //转成bae64编码  
                       callback(data);  
                   });   
               };   
               reader.readAsDataURL(fileObj);    
           } catch(e) {    
               console.log("压缩失败!");    
               //调用直接上传方式  不压缩   
               directTurnIntoBase64(fileObj,callback);   
           }    
       }  
   }    
  
   //对图片旋转处理 added by lzk    
   function rotateImg(img, direction,canvas) {      
       //alert(img);    
       //最小与最大旋转方向，图片旋转4次后回到原方向      
       var min_step = 0;      
       var max_step = 4;      
       //var img = document.getElementById(pid);      
       if (img == null)return;      
       //img的高度和宽度不能在img元素隐藏后获取，否则会出错      
       var height = img.height;      
       var width = img.width;      
       //var step = img.getAttribute('step');      
       var step = 2;      
       if (step == null) {      
           step = min_step;      
       }      
       if (direction == 'right') {      
           step++;      
           //旋转到原位置，即超过最大值      
           step > max_step && (step = min_step);      
       } else if(direction == 'half'){  
    
       } else{      
           step--;      
           step < min_step && (step = max_step);      
       }      
       //img.setAttribute('step', step);      
       /*var canvas = document.getElementById('pic_' + pid);     
       if (canvas == null) {     
           img.style.display = 'none';     
           canvas = document.createElement('canvas');     
           canvas.setAttribute('id', 'pic_' + pid);     
           img.parentNode.appendChild(canvas);     
       }  */    
       //旋转角度以弧度值为参数      
       var degree = step * 90 * Math.PI / 180;      
       var ctx = canvas.getContext('2d');      
       switch (step) {      
           case 0:      
               canvas.width = width;      
               canvas.height = height;      
               ctx.drawImage(img, 0, 0);      
               break;      
           case 1:      
               canvas.width = height;      
               canvas.height = width;      
               ctx.rotate(degree);      
               ctx.drawImage(img, 0, -height);      
               break;      
           case 2:      
               canvas.width = width;      
               canvas.height = height;      
               ctx.rotate(degree);      
               ctx.drawImage(img, -width, -height);      
               break;      
           case 3:      
               canvas.width = height;      
               canvas.height = width;      
               ctx.rotate(degree);      
               ctx.drawImage(img, -width, 0);      
               break;      
       }      
   } 